package com.whosly.mysql.protocol.packet.impl;

import com.whosly.mysql.protocol.jdbc.MySQLMessage;
import com.whosly.mysql.protocol.packet.jdbc.MySQLPacket;
import com.whosly.mysql.protocol.packet.util.NettyBufferUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import lombok.Getter;

/**
 * @author fengyang
 * @date 2023/7/20 下午3:14
 * @see <a href="yueny09@163.com">mailTo: yueny09@163.com</a>
 */
public class LocalInfilePacket extends MySQLPacket
{
    public byte resultPackType = PACKET_LOCAL_INFILE;

    @Getter
    protected String filePath;

    @Override
    public void read(byte[] bodyBytes)
    {
        readBody(new MySQLMessage(bodyBytes));
    }

    private void readBody(MySQLMessage mm) {
        resultPackType = mm.read();
        filePath = mm.readStringWithLength();
    }

    @Override
    public ByteBuf writeBuf(ByteBuf buffer)
    {
        NettyBufferUtil.writeUB3(buffer, buffer.capacity());
        buffer.writeByte(getPackId());

        writeBody(buffer);

        return buffer;
    }

    @Override
    public ByteBuf writeBuf()
    {
        ByteBuf buffer = Unpooled.buffer(calcPacketSize());

        return writeBuf(buffer);
    }

    private void writeBody(ByteBuf buffer){
        buffer.writeByte(resultPackType);
        NettyBufferUtil.writeWithLength(buffer, filePath);
    }

    @Override
    public int calcPacketSize()
    {
        int packLength = 1; // resultPackType len
        packLength += filePath == null ? 0 : filePath.length() * 2;
        return packLength;
    }
}
